package core.io;

import core.utils.HttpProtocolUtil;
import core.utils.StaticResourceUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 封装Response，提供输出信息
 * @author wsz
 * @date 2021/11/12 17:27
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Response {

    private OutputStream outputStream;

    /**
     * 封装字符串
     * @param content
     * @return
     * @throws IOException
     */
    public OutputStream output(String content) throws IOException {
        if (content == null) return outputStream;
        outputStream.write(HttpProtocolUtil.responseText(content));
        return this.outputStream;
    }

    public OutputStream outputHtml(Request resquest) throws IOException {
        String absolutePath = StaticResourceUtil.getAbsolutePath(resquest);
        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {
            // 读取并输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 静态资源不存在：404
            output(HttpProtocolUtil.getHttpHeader404());
        }
        return this.outputStream;
    }

    /**
     * 封装静态资源文件如html
     * @param path
     * @return
     */
    public OutputStream outputHtml(String path) throws IOException {
        String absolutePath = StaticResourceUtil.getAbsolutePath(path);
        File file = new File(absolutePath);
        if (file.exists() && file.isFile()) {
            // 读取并输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), outputStream);
        } else {
            // 静态资源不存在：404
            output(HttpProtocolUtil.getHttpHeader404());
        }
        return this.outputStream;
    }
}
